package edu.math.chaos.itfunc.ui;

import edu.math.chaos.itfunc.api.Parameters;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.ScrollPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

import java.io.IOException;
import java.util.List;

/**
 * User: Илья
 * Date: 09.11.13
 * Time: 13:03
 */
public class BoardController {

	@FXML
	private ScrollPane scroller;

	private void draw(List<int[]> dots, Parameters params) {
		Canvas canvas = new Canvas(params.getWidth() * RECT_SIZE, params.getHeight() * RECT_SIZE);
		scroller.setContent(canvas);

		GraphicsContext context = canvas.getGraphicsContext2D();
		context.setStroke(Color.BLACK);
		for (int[] dot : dots) {
			double x = dot[0] * RECT_SIZE;
			double y = dot[1] * RECT_SIZE;
			context.fillRect(x, y, RECT_SIZE, RECT_SIZE);
		}
	}

	@FXML
	private void change() {
		stage.close();
		ParametersController.showParameters();
	}

	private static final String FXML_PATH = "Board.fxml";
	private static final String TITLE = UIApplication.makeStageTitle("Фрактал");

	private static final double RECT_SIZE = 1;

	private static Stage stage;

	public static void showBoard(List<int[]> dots, Parameters params) {
		if (dots == null || dots.isEmpty() || params == null || params.checkParameters() != null) {
			return;
		}

		FXMLLoader loader = new FXMLLoader(BoardController.class.getResource(FXML_PATH));
		try {
			Parent root = (Parent) loader.load();
			stage = new Stage();
			stage.setTitle(TITLE);
			stage.setScene(new Scene(root, 700, 500));
			stage.show();
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}

		BoardController controller = loader.<BoardController>getController();
		if (controller == null) {
			return;
		}

		controller.draw(dots, params);
	}
}
